package com.biglead.admin.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.biglead.admin.mapper.*;
import com.biglead.admin.param.PmsProductParam;
import com.biglead.admin.param.PmsProductQueryParam;
import com.biglead.admin.param.PmsProductResult;
import com.biglead.admin.pojo.*;
import com.biglead.admin.service.PmsProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service("productService")
@Slf4j
public class PmsProductServiceImpl extends ServiceImpl<PmsProductMapper, PmsProduct> implements PmsProductService {

    @Autowired
    private PmsProductDao pmsProductDao;
    @Autowired
    private PmsMemberPriceDao memberPriceDao;
    @Autowired
    private ProductLadderDao productLadderDao;
    @Autowired
    private ProductFullReductionDao productFullReductionDao;
    @Autowired
    private SkuStockDao skuStockDao;
    @Autowired
    private ProductAttributeValueDao productAttributeValueDao;

    @Autowired
    private SubjectProductRelationDao subjectProductRelationDao;
    @Autowired
    private PrefrenceAreaProductRelationDao prefrenceAreaProductRelationDao;

    @Override
    @Transactional
    public boolean create(PmsProductParam productParam) {


        //创建商品
        PmsProduct product = productParam;
        product.setId(null);
        this.save(product);
        //根据促销类型设置价格：会员价格、阶梯价格、满减价格
        Long productId = product.getId();
        //会员价格
        relateAndInsertList(memberPriceDao, productParam.getMemberPriceList(), productId);
        //阶梯价格
        relateAndInsertList(productLadderDao, productParam.getProductLadderList(), productId);
        //满减价格
        relateAndInsertList(productFullReductionDao, productParam.getProductFullReductionList(), productId);
        //处理sku的编码
        handleSkuStockCode(productParam.getSkuStockList(), productId);
        //添加sku库存信息
        relateAndInsertList(skuStockDao, productParam.getSkuStockList(), productId);
        //添加商品参数,添加自定义商品规格
        relateAndInsertList(productAttributeValueDao, productParam.getProductAttributeValueList(), productId);
        //关联专题
        relateAndInsertList(subjectProductRelationDao, productParam.getSubjectProductRelationList(), productId);
        //关联优选
        relateAndInsertList(prefrenceAreaProductRelationDao, productParam.getPrefrenceAreaProductRelationList(), productId);

        return false;
    }

    @Override
    public PmsProductResult getUpdateInfo(Long id) {
        return pmsProductDao.getUpdateInfo(id);
    }

    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private PmsMemberPriceMapper pmsMemberPriceMapper;
    @Autowired
    private PmsProductLadderMapper pmsProductLadderMapper;
    @Autowired
    private PmsProductFullReductionMapper pmsProductFullReductionMapper;
    @Autowired
    private PmsProductAttributeValueMapper pmsProductAttributeValueMapper;
    @Autowired
    private CmsSubjectProductRelationMapper cmsSubjectProductRelationMapper;

    @Autowired
    private CmsPrefrenceAreaProductRelationMapper cmsPrefrenceAreaProductRelationMapper;

    @Override
    @Transactional
    public boolean update(Long id, PmsProductParam productParam) {
        //更新商品信息
        PmsProduct product = productParam;
        product.setId(id);
        this.updateById(product);
        //会员价格
        //删除旧的
        pmsMemberPriceMapper.delete(new LambdaQueryWrapper<PmsMemberPrice>()
                .eq(PmsMemberPrice::getProductId, id));
        //新增
        relateAndInsertList(memberPriceDao, productParam.getMemberPriceList(), id);


        //阶梯价格
        pmsProductLadderMapper.delete(new LambdaQueryWrapper<PmsProductLadder>()
                .eq(PmsProductLadder::getProductId, id));

        relateAndInsertList(productLadderDao, productParam.getProductLadderList(), id);


        //满减价格
        pmsProductFullReductionMapper.delete(new LambdaQueryWrapper<PmsProductFullReduction>()
                .eq(PmsProductFullReduction::getProductId, id));
        relateAndInsertList(productFullReductionDao, productParam.getProductFullReductionList(), id);


        //修改sku库存信息
        handleUpdateSkuStockList(id, productParam);
        //修改商品参数,添加自定义商品规格
        pmsProductAttributeValueMapper.delete(new LambdaQueryWrapper<PmsProductAttributeValue>()
                .eq(PmsProductAttributeValue::getProductId, id));
        relateAndInsertList(productAttributeValueDao, productParam.getProductAttributeValueList(), id);


        //关联专题
        cmsSubjectProductRelationMapper.delete(new LambdaQueryWrapper<CmsSubjectProductRelation>()
                .eq(CmsSubjectProductRelation::getProductId, id));
        relateAndInsertList(subjectProductRelationDao, productParam.getSubjectProductRelationList(), id);


        //关联优选
        cmsPrefrenceAreaProductRelationMapper.delete(new LambdaQueryWrapper<CmsPrefrenceAreaProductRelation>()
                .eq(CmsPrefrenceAreaProductRelation::getProductId, id));

        relateAndInsertList(prefrenceAreaProductRelationDao, productParam.getPrefrenceAreaProductRelationList(), id);
        return true;
    }

    @Override
    public Page<PmsProduct> pageList(PmsProductQueryParam productQueryParam, Integer pageSize, Integer pageNum) {

        Page<PmsProduct> page = Page.of(pageNum, pageSize);
        //queryWrapper组装查询where条件
        LambdaQueryWrapper<PmsProduct> queryWrapper = new LambdaQueryWrapper<>();
        //查询条件 未删除的商品
        queryWrapper.eq(PmsProduct::getDeleteStatus, 0);
        queryWrapper.eq(productQueryParam.getPublishStatus() != null, PmsProduct::getPublishStatus, productQueryParam.getPublishStatus());

        queryWrapper.eq(productQueryParam.getVerifyStatus() != null, PmsProduct::getVerifyStatus, productQueryParam.getVerifyStatus());

        queryWrapper.like(StringUtils.isNotEmpty(productQueryParam.getKeyword()), PmsProduct::getName, productQueryParam.getKeyword());

        queryWrapper.eq(StringUtils.isNotEmpty(productQueryParam.getProductSn()), PmsProduct::getProductSn, productQueryParam.getProductSn());
        queryWrapper.eq(productQueryParam.getBrandId() != null, PmsProduct::getBrandId, productQueryParam.getBrandId());

        queryWrapper.eq(productQueryParam.getProductCategoryId() != null, PmsProduct::getProductCategoryId, productQueryParam.getProductCategoryId());
        //发起查询
        this.page(page, queryWrapper);
        return page;
    }

    @Override
    public List<PmsProduct> list(String keyword) {
        return this.list(new LambdaQueryWrapper<PmsProduct>().like(PmsProduct::getName, keyword));
    }
    @Autowired
    private PmsProductVertifyRecordDao pmsProductVertifyRecordDao;
    @Override
    @Transactional
    public boolean updateVerifyStatus(List<Long> ids, Integer verifyStatus, String detail) {
        UpdateWrapper<PmsProduct> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id",ids);
        PmsProduct product = new PmsProduct();
        product.setVerifyStatus(verifyStatus);
        boolean i = this.update(product,updateWrapper);
        List<PmsProductVertifyRecord> list = new ArrayList<>();
        //修改完审核状态后插入审核记录
        for (Long id : ids) {
            PmsProductVertifyRecord record = new PmsProductVertifyRecord();
            record.setProductId(id);
            record.setCreateTime(new Date());
            record.setDetail(detail);
            record.setStatus(verifyStatus);
            record.setVertifyMan("test");
            list.add(record);
        }
        pmsProductVertifyRecordDao.insertList(list);
        return  i;
    }

    @Override
    public boolean updatePublishStatus(List<Long> ids, Integer publishStatus) {
        UpdateWrapper<PmsProduct> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id",ids);
        PmsProduct product = new PmsProduct();
        product.setPublishStatus(publishStatus);
        boolean i = this.update(product,updateWrapper);
        return i;
    }

    @Override
    public boolean updateRecommendStatus(List<Long> ids, Integer recommendStatus) {
        UpdateWrapper<PmsProduct> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id",ids);
        PmsProduct product = new PmsProduct();
        product.setRecommandStatus(recommendStatus);
        boolean i = this.update(product,updateWrapper);
        return i;
    }

    @Override
    public boolean updateNewStatus(List<Long> ids, Integer newStatus) {
        UpdateWrapper<PmsProduct> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id",ids);
        PmsProduct product = new PmsProduct();
        product.setNewStatus(newStatus);
        boolean i = this.update(product,updateWrapper);
        return i;
    }

    @Override
    public boolean updateDeleteStatus(List<Long> ids, Integer deleteStatus) {
        UpdateWrapper<PmsProduct> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id",ids);
        PmsProduct product = new PmsProduct();
        product.setDeleteStatus(deleteStatus);
        boolean i = this.update(product,updateWrapper);
        return i;
    }

    private void handleSkuStockCode(List<PmsSkuStock> skuStockList, Long productId) {
        if (CollectionUtils.isEmpty(skuStockList)) return;
        for (int i = 0; i < skuStockList.size(); i++) {
            PmsSkuStock skuStock = skuStockList.get(i);
            if (StringUtils.isEmpty(skuStock.getSkuCode())) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                StringBuilder sb = new StringBuilder();
                //日期
                sb.append(sdf.format(new Date()));
                //四位商品id
                sb.append(String.format("%04d", productId));
                //三位索引id
                sb.append(String.format("%03d", i + 1));
                skuStock.setSkuCode(sb.toString());
            }
        }
    }

    private void handleUpdateSkuStockList(Long id, PmsProductParam productParam) {
        //当前的sku信息
        List<PmsSkuStock> currSkuList = productParam.getSkuStockList();
        //当前没有sku直接删除
        if (currSkuList == null || currSkuList.isEmpty()) {
            skuStockMapper.delete(new LambdaQueryWrapper<PmsSkuStock>()
                    .eq(PmsSkuStock::getProductId, id));
            return;
        }
        //获取初始sku信息

        List<PmsSkuStock> oriStuList = skuStockMapper.selectList(new LambdaQueryWrapper<PmsSkuStock>()
                .eq(PmsSkuStock::getProductId, id));
        //获取新增sku信息
        List<PmsSkuStock> insertSkuList = currSkuList.stream().filter(item -> item.getId() == null).collect(Collectors.toList());
        //获取需要更新的sku信息
        List<PmsSkuStock> updateSkuList = currSkuList.stream().filter(item -> item.getId() != null).collect(Collectors.toList());
        List<Long> updateSkuIds = updateSkuList.stream().map(PmsSkuStock::getId).collect(Collectors.toList());
        //获取需要删除的sku信息
        List<PmsSkuStock> removeSkuList = oriStuList.stream().filter(item -> !updateSkuIds.contains(item.getId())).collect(Collectors.toList());
        handleSkuStockCode(insertSkuList, id);
        handleSkuStockCode(updateSkuList, id);
        //新增sku
        if (!insertSkuList.isEmpty()) {
            relateAndInsertList(skuStockDao, insertSkuList, id);
        }
        //删除sku
        if (!removeSkuList.isEmpty()) {
            List<Long> removeSkuIds = removeSkuList
                    .stream()
                    .map(PmsSkuStock::getId)
                    .collect(Collectors.toList());
            skuStockMapper.delete(new LambdaQueryWrapper<PmsSkuStock>()
                    .in(PmsSkuStock::getId, removeSkuIds));
        }
        //修改sku
        if (!updateSkuList.isEmpty()) {
            for (PmsSkuStock pmsSkuStock : updateSkuList) {
                skuStockMapper.updateById(pmsSkuStock);
            }
        }

    }

    /**
     * 建立和插入关系表操作
     *
     * @param dao       可以操作的dao
     * @param dataList  要插入的数据
     * @param productId 建立关系的id
     */
    private void relateAndInsertList(Object dao, List dataList, Long productId) {
        try {
            if (CollectionUtils.isEmpty(dataList)) return;
            for (Object item : dataList) {
                Method setId = item.getClass().getMethod("setId", Long.class);
                setId.invoke(item, (Long) null);
                Method setProductId = item.getClass().getMethod("setProductId", Long.class);
                setProductId.invoke(item, productId);
            }
            Method insertList = dao.getClass().getMethod("insertList", List.class);
            insertList.invoke(dao, dataList);
        } catch (Exception e) {
            log.warn("创建产品出错:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }
}
